<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/myblog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/myblog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/myblog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/myblog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/myblog/css/main.css">


<link rel="stylesheet" href="/myblog/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/myblog/lib/pace/pace-theme-minimal.min.css">
  <script src="/myblog/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gao-qianwei.gitee.io","root":"/myblog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="一、基本概念&amp;ensp;&amp;ensp;&amp;ensp;&amp;ensp;MySQL从8.0开始支持窗口函数，这个功能在大多商业数据库和部分开源数据库中早已支持，有的也叫分析函数。">
<meta property="og:type" content="article">
<meta property="og:title" content="MySql8.0窗口函数">
<meta property="og:url" content="https://gao-qianwei.gitee.io/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/index.html">
<meta property="og:site_name" content="学无止境">
<meta property="og:description" content="一、基本概念&amp;ensp;&amp;ensp;&amp;ensp;&amp;ensp;MySQL从8.0开始支持窗口函数，这个功能在大多商业数据库和部分开源数据库中早已支持，有的也叫分析函数。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/1.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/2.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/3.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/4.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/5.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/6.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/7.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/8.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/9.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/10.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/11.png">
<meta property="og:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/12.png">
<meta property="article:published_time" content="2021-04-21T00:26:35.000Z">
<meta property="article:modified_time" content="2021-04-30T12:26:39.356Z">
<meta property="article:author" content="高乾威">
<meta property="article:tag" content="数据库">
<meta property="article:tag" content="窗口函数">
<meta property="article:tag" content="MySql">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gao-qianwei.gitee.io/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/1.png">

<link rel="canonical" href="https://gao-qianwei.gitee.io/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>MySql8.0窗口函数 | 学无止境</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/myblog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">学无止境</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/myblog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/myblog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/myblog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/myblog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/myblog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-links">

    <a href="/myblog/links/" rel="section"><i class="fa fa-link fa-fw"></i>友链</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gao-qianwei.gitee.io/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/myblog/images/avatar.png">
      <meta itemprop="name" content="高乾威">
      <meta itemprop="description" content="报我楼成秋望月，把君诗读夜回灯">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          MySql8.0窗口函数
        </h1>

        <div class="post-meta">

          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-04-21 08:26:35" itemprop="dateCreated datePublished" datetime="2021-04-21T08:26:35+08:00">2021-04-21</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-04-30 20:26:39" itemprop="dateModified" datetime="2021-04-30T20:26:39+08:00">2021-04-30</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblog/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" itemprop="url" rel="index"><span itemprop="name">数据库</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblog/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/MySql/" itemprop="url" rel="index"><span itemprop="name">MySql</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
            <span class="post-meta-divider">|</span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="一、基本概念"><a href="#一、基本概念" class="headerlink" title="一、基本概念"></a>一、基本概念</h3><p>&ensp;&ensp;&ensp;&ensp;MySQL从<strong>8.0</strong>开始支持窗口函数，这个功能在大多商业数据库和部分开源数据库中早已支持，有的也叫分析函数。</p>
 <span id="more"></span>

<p>概念：</p>
<p>&ensp;&ensp;&ensp;&ensp;<strong>窗口</strong>的概念可以理解为记录集合；<strong>窗口函数</strong>也就是在满足某种条件的记录集合上执行的特殊函数，对于每条记录都要在此窗口内执行函数，有的函数随着记录不同，窗口大小都是固定的，这种是静态窗口；有的函数则是不同的记录对应着不同的窗口，这种动态变化的窗口叫滑动窗口。</p>
<p>窗口函数与聚合函数：</p>
<ol>
<li>聚合函数是将多条记录聚合为一条；</li>
<li>窗口函数是每条记录都会执行，有几条记录执行完还是几条；</li>
<li>聚合函数也可以用于窗口函数。</li>
</ol>
<h3 id="二、基本格式"><a href="#二、基本格式" class="headerlink" title="二、基本格式"></a>二、基本格式</h3><p>基本语法：&lt;窗口函数&gt; over (子句)</p>
<ul>
<li><p>&lt;窗口函数&gt;的位置可以放专用窗口函数（rank()，percent_rank()，dense_rank()等），或者放聚合函数（sum()，avg()，max()等）。</p>
</li>
<li><p>窗口函数是对where或group by子句处理后的结果进行操作，故其原则上只写于SELECT子句中。</p>
</li>
<li><p>over 用来指定函数执行的窗口范围，<strong>若子句为空</strong>，则意味着窗口包含满足WHERE条件的所有行，窗口函数基于所有行进行计算。</p>
</li>
<li><p>若子句非空，则支持以下4中语法来设置窗口：</p>
<p>​        <strong>window_name</strong>：给窗口指定一个别名，如果SQL中涉及的窗口较多，采用别名可以看起来更清晰易读。        </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	&#96;姓名&#96;,</span><br><span class="line">	&#96;班级&#96;,</span><br><span class="line">	&#96;人气&#96;,</span><br><span class="line">	rank() over w1 AS rak</span><br><span class="line">FROM</span><br><span class="line">	&#96;民工漫班级&#96; window w1 AS ( PARTITION BY &#96;班级&#96; ORDER BY &#96;人气&#96; DESC );</span><br></pre></td></tr></table></figure>

<p>​        结果：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/1.png" alt="image-20201217104056497" style="zoom:80%;">

<p>​        <strong>partition子句</strong>：窗口按照那些字段进行分组，窗口函数在不同的分组上分别执行。</p>
<p>​        <strong>order by子句</strong>：按照哪些字段进行排序，窗口函数将按照排序后的记录顺序进行编号。</p>
<p>​        frame子句：frame是当前分区的一个子集，子句用来定义子集的规则，通常用来作为滑动窗口使用。（本文暂不介绍）</p>
<p>​        用于操作示例新建的民工漫班级表：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/2.png" alt="民工漫班级" style="zoom: 67%;">

<p>​        </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	*,</span><br><span class="line">	RANK() over ( PARTITION BY &#96;班级&#96; ORDER BY &#96;人气&#96; DESC ) AS ranking </span><br><span class="line">FROM</span><br><span class="line">	&#96;民工漫班级&#96;;</span><br><span class="line"># PARTITION BY &#96;班级&#96;：按班级分组（使用group by会改变表的行数，一个类别只保留一行；partition by则不会减少表的行数）</span><br><span class="line"># ORDER BY &#96;人气&#96; DESC：对按班级分组后的结果按人气降序排名，名次作为字段 ranking</span><br></pre></td></tr></table></figure>

<p>得到结果：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/3.png" alt="image-20201217000959621" style="zoom: 50%;"></li>
</ul>
<h3 id="三、mysql窗口函数"><a href="#三、mysql窗口函数" class="headerlink" title="三、mysql窗口函数"></a>三、mysql窗口函数</h3><p><strong>功能划分</strong>：</p>
<p> 按功能划分可将MySQL支持的窗口函数分为如下几类：</p>
<ol>
<li>序号函数：ROW_NUMBER()、RANK()、DENSE_RANK()</li>
<li>分布函数：PERCENT_RANK()、CUME_DIST()，PERCENT_RANK()</li>
<li>前后函数：LAG(expr,n)、LEAD(expr,n)</li>
<li>头尾函数：FIRST_VALUE(expr)、LAST_VALUE(expr)</li>
<li>其它函数：NTH_VALUE(expr, n)、NTILE(n)</li>
</ol>
<p><strong>分别介绍：</strong></p>
<p><strong>序号函数：ROW_NUMBER()、RANK()、DENSE_RANK()</strong></p>
<p>&ensp;&ensp;&ensp;&ensp;举个例子，还用上面的民工漫班级表，用三个函数按人气对其排序：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	*,</span><br><span class="line">	RANK() over (  ORDER BY &#96;人气&#96; DESC ) AS &#96;rank&#96; ,</span><br><span class="line">	DENSE_RANK() over (  ORDER BY &#96;人气&#96; DESC ) AS &#96;dense_rank&#96; ,</span><br><span class="line">	ROW_NUMBER() over (  ORDER BY &#96;人气&#96; DESC ) AS &#96;row_number&#96; </span><br><span class="line">FROM</span><br><span class="line">	&#96;民工漫班级&#96;;</span><br></pre></td></tr></table></figure>

<p>&ensp;&ensp;&ensp;&ensp;结果：没有再用partition by对班级分组</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/4.png" alt="image-20201217004449218" style="zoom: 67%;">

<p>由此可知：</p>
<ul>
<li>RANK()：并列排序，跳过重复序号——1、1、3</li>
<li>DENSE_RANK()：并列排序，不跳过重复序号——1、1、2</li>
<li>ROW_NUMBER()：顺序排序——1、2、3；相当于行号。</li>
</ul>
<p><strong>分布函数：PERCENT_RANK()、CUME_DIST()</strong></p>
<p><strong>percent_rank()</strong></p>
<p>&ensp;&ensp;&ensp;&ensp;用途：和之前的RANK()函数相关，每行按照如下公式进行计算：(rank - 1) / (rows - 1)， 其中，rank为RANK()函数产生的序号，rows为当前窗口的记录总行数 该函数可以用来计算分位数。</p>
<p>&ensp;&ensp;&ensp;&ensp;继续举例子（想不到实际生活的应用场景）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	*,</span><br><span class="line">	RANK() OVER w AS rankNo,</span><br><span class="line">	PERCENT_RANK() OVER w AS percent_rankNo </span><br><span class="line">FROM</span><br><span class="line">	&#96;民工漫班级&#96; WINDOW w AS ( ORDER BY &#96;人气&#96; DESC );</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/5.png" alt="image-20201217105136040" style="zoom: 50%;">

<p>&ensp;&ensp;&ensp;&ensp;对于路飞，percent_rankNo = (rank - 1) / (rows - 1) =(3 - 1) / (10 - 1) =0.22222222……</p>
<p><strong>CUME_DIST()</strong></p>
<p>&ensp;&ensp;&ensp;&ensp;用途：分组内小于、等于当前rank值的行数 / 分组内总行数</p>
<p>&ensp;&ensp;&ensp;&ensp;举例：查询小于等于当前人气的比例（或者说某人是前百分之几，生活中很常用）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	*,</span><br><span class="line">	CUME_DIST() OVER w AS cdt </span><br><span class="line">FROM</span><br><span class="line">	&#96;民工漫班级&#96; WINDOW w AS ( ORDER BY &#96;人气&#96; DESC );</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/6.png" alt="image-20201217110444956" style="zoom: 67%;">

<p><strong>前后函数：LAG(expr,n)、LEAD(expr,n)</strong></p>
<p>&ensp;&ensp;&ensp;&ensp;用途：返回位于当前行的前n行（LAG(expr,n)）或后n行（LEAD(expr,n)）的expr的值（以当前行为原点）</p>
<p>&ensp;&ensp;&ensp;&ensp;例：这个生活中应该挺常用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	*,</span><br><span class="line">	&#96;我的前面一名人气&#96; - &#96;人气&#96; AS &#96;我和前面一名的差距&#96;,</span><br><span class="line">	&#96;人气&#96; - &#96;后面一名人气&#96; AS &#96;我甩开后面一名多少差距&#96; </span><br><span class="line">FROM</span><br><span class="line">	(</span><br><span class="line">	SELECT</span><br><span class="line">		*,</span><br><span class="line">		LAG( &#96;人气&#96;, 1 ) OVER w AS &#96;我的前面一名人气&#96;,# 取前面第一行的人气值</span><br><span class="line">		LEAD( &#96;人气&#96;, 1 ) OVER w AS &#96;后面一名人气&#96; # 取后面第一行的人气值</span><br><span class="line">		</span><br><span class="line">	FROM</span><br><span class="line">		&#96;民工漫班级&#96; WINDOW w AS ( ORDER BY &#96;人气&#96; DESC ) </span><br><span class="line">	) t;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/7.png" alt="image-20201217113619889" style="zoom: 67%;">

<p>&ensp;&ensp;&ensp;&ensp;蓝染的前1行是路飞，其人气为90，差距为2；后一行是佐助，甩开他1人气。</p>
<p><strong>头尾函数：FIRST_VALUE(expr),LAST_VALUE(expr)</strong></p>
<p>&ensp;&ensp;&ensp;&ensp;用途：返回第一个（FIRST_VALUE(expr)）或最后一个（LAST_VALUE(expr)）expr的值</p>
<p>&ensp;&ensp;&ensp;&ensp;例：截止到当前人气，按人气排名，第一名和最后一名是多少（降序排，最后一名肯定是自己）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	*,</span><br><span class="line">	FIRST_VALUE( &#96;人气&#96; ) OVER w AS &#96;当前第一人气值&#96;,</span><br><span class="line">	LAST_VALUE( &#96;人气&#96; ) OVER w AS &#96;当前倒数第一人气值&#96; </span><br><span class="line">FROM</span><br><span class="line">	&#96;民工漫班级&#96; WINDOW w AS ( ORDER BY &#96;人气&#96; DESC );</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/8.png" alt="image-20201217114336947" style="zoom: 67%;">

<p><strong>其它函数：NTH_VALUE(expr, n)、NTILE(n)</strong></p>
<p><strong>NTH_VALUE(expr, n)</strong></p>
<p>&ensp;&ensp;&ensp;&ensp;用途：返回窗口中第N个expr的值，expr可以是表达式，也可以是列名。</p>
<p>&ensp;&ensp;&ensp;&ensp;例：截至当前人气，显示每个人物的人气中排名第2、第4、第6的人气值</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	*,</span><br><span class="line">	NTH_VALUE( &#96;人气&#96;, 2 ) OVER w AS &#96;第二人气值&#96;,</span><br><span class="line">	NTH_VALUE( &#96;人气&#96;, 4 ) OVER w AS &#96;第四人气值&#96;,</span><br><span class="line">	NTH_VALUE( &#96;人气&#96;, 6 ) OVER w AS &#96;第六人气值&#96; </span><br><span class="line">FROM</span><br><span class="line">	&#96;民工漫班级&#96; WINDOW w AS ( ORDER BY &#96;人气&#96; DESC );</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>结果：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/9.png" alt="image-20201217135748608" style="zoom: 67%;">

<p><strong>NTILE(n)</strong></p>
<p>&ensp;&ensp;&ensp;&ensp;用途：将分区中的有序数据分为n个等级，记录等级数</p>
<p>例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	*,</span><br><span class="line">	ROW_NUMBER() OVER w AS &#39;row_number&#39;,</span><br><span class="line">	NTILE( 2 ) OVER w AS &#39;ntile2&#39;,</span><br><span class="line">	NTILE( 4 ) OVER w AS &#39;ntile4&#39; </span><br><span class="line">FROM</span><br><span class="line">	&#96;民工漫班级&#96; WINDOW w AS ( ORDER BY &#96;人气&#96; );</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/10.png" alt="image-20201217170421940" style="zoom:67%;">

<h3 id="四、用聚合函数作为窗口函数"><a href="#四、用聚合函数作为窗口函数" class="headerlink" title="四、用聚合函数作为窗口函数"></a>四、用聚合函数作为窗口函数</h3><p>&ensp;&ensp;&ensp;&ensp;用途：在窗口中每条记录动态地应用聚合函数（SUM()、AVG()、MAX()、MIN()、COUNT()），可以动态计算在指定的窗口内的各种聚合函数值</p>
<p>例：普通使用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	*,</span><br><span class="line">	sum( &#96;人气&#96; )  AS current_sum,</span><br><span class="line">	avg( &#96;人气&#96; )  AS current_avg,</span><br><span class="line">	count( &#96;人气&#96; )  AS current_count,</span><br><span class="line">	max( &#96;人气&#96; )  AS current_max,</span><br><span class="line">	min( &#96;人气&#96; ) AS current_min </span><br><span class="line">FROM</span><br><span class="line">	&#96;民工漫班级&#96;;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/11.png" alt="image-20201217172447565" style="zoom: 67%;">

<p>&ensp;&ensp;&ensp;&ensp;按学号排序，作为窗口函数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	*,</span><br><span class="line">	sum( &#96;人气&#96; ) over w AS current_sum,</span><br><span class="line">	avg( &#96;人气&#96; ) over w AS current_avg,</span><br><span class="line">	count( &#96;人气&#96; ) over w AS current_count,</span><br><span class="line">	max( &#96;人气&#96; ) over w AS current_max,</span><br><span class="line">	min( &#96;人气&#96; ) over w AS current_min </span><br><span class="line">FROM</span><br><span class="line">	&#96;民工漫班级&#96; WINDOW w AS ( ORDER BY &#96;学号&#96; );</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<img src="/myblog/myblog/2021/04/21/%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%9AMySql8.0%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/12.png" alt="image-20201217172207911" style="zoom:67%;">

<p>&ensp;&ensp;&ensp;&ensp;以current_sum为例，每一行current_sum的值为上面所有行的<code>人气</code>值之和。</p>
<p>本文主要参考：</p>
<p><a target="_blank" rel="noopener" href="https://dev.mysql.com/doc/refman/8.0/en/">《MySql8.0参考手册》</a></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/myblog/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/" rel="tag"># 数据库</a>
              <a href="/myblog/tags/%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/" rel="tag"># 窗口函数</a>
              <a href="/myblog/tags/MySql/" rel="tag"># MySql</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/myblog/2021/04/10/top%EF%BC%9A%E8%AF%B4%E6%98%8E/" rel="prev" title="近期说明">
      <i class="fa fa-chevron-left"></i> 近期说明
    </a></div>
      <div class="post-nav-item">
    <a href="/myblog/2021/04/21/%E7%AE%97%E6%B3%95%EF%BC%9A%E7%BC%BA%E5%A4%B1%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E6%AD%A3%E6%95%B0/" rel="next" title="缺失的第一个整数">
      缺失的第一个整数 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="nav-text">一、基本概念</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%9F%BA%E6%9C%AC%E6%A0%BC%E5%BC%8F"><span class="nav-text">二、基本格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%89%E3%80%81mysql%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0"><span class="nav-text">三、mysql窗口函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9B%9B%E3%80%81%E7%94%A8%E8%81%9A%E5%90%88%E5%87%BD%E6%95%B0%E4%BD%9C%E4%B8%BA%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0"><span class="nav-text">四、用聚合函数作为窗口函数</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="高乾威"
      src="/myblog/images/avatar.png">
  <p class="site-author-name" itemprop="name">高乾威</p>
  <div class="site-description" itemprop="description">报我楼成秋望月，把君诗读夜回灯</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/myblog/archives/">
        
          <span class="site-state-item-count">91</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/myblog/categories/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/myblog/tags/">
          
        <span class="site-state-item-count">59</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="http://github.com/GaoQianwei" title="GitHub → http:&#x2F;&#x2F;github.com&#x2F;GaoQianwei" rel="noopener" target="_blank">GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:2966807184@qq.com" title="E-Mail → mailto:2966807184@qq.com" rel="noopener" target="_blank">E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.zhihu.com/people/xue-wu-zhi-jing-75-22" title="知乎 → https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;xue-wu-zhi-jing-75-22" rel="noopener" target="_blank">知乎</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/weixin_45341339" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;weixin_45341339" rel="noopener" target="_blank">CSDN</a>
      </span>
  </div>



      </div><div>
  <canvas id="canvasDiyBlock" style="width:60%;">当前浏览器不支持canvas，请更换浏览器后再试</canvas>
<script src="/myblog/js/custom/clock.js"></script>

</div>


    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2021-04 到 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">高乾威</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

<span class="post-meta-divider">|</span>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">全站共 117.2k 字</span>
</div>

<span class="post-meta-divider">|</span>
        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/myblog/lib/anime.min.js"></script>
  <script src="/myblog/lib/velocity/velocity.min.js"></script>
  <script src="/myblog/lib/velocity/velocity.ui.min.js"></script>

<script src="/myblog/js/utils.js"></script>

<script src="/myblog/js/motion.js"></script>


<script src="/myblog/js/schemes/pisces.js"></script>


<script src="/myblog/js/next-boot.js"></script>


  <script defer src="/myblog/lib/three/three.min.js"></script>
    <script defer src="/myblog/lib/three/canvas_lines.min.js"></script>


  




  
<script src="/myblog/js/local-search.js"></script>













  

  

</body>
</html>
